<template>
  <div class="top" style="overflow-x: hidden">
    <el-row :gutter="10" v-if="imageList.length > 0">
      <el-col
        :span="6"
        :offset="0"
        v-for="(item, index) in imageList"
        :key="index"
      >
        <el-card
          shadow="hover"
          class="relative mb-3"
          :body-style="{ padding: 0 }"
          :class="{ 'border-blue-500': item.checked }"
        >
          <el-image
            :src="item.url"
            fit="cover"
            class="h-[150px]"
            style="width: 100%"
            :preview-src-list="[item.url]"
            :initial-index="0"
          ></el-image>
          <div class="image-title">{{ item.name }}</div>
          <div class="flex items-center justify-center p-2">
            <el-checkbox
              v-if="openChoose"
              v-model="item.checked"
              @change="handleChooseChange(item)"
            />

            <el-button
              type="primary"
              size="small"
              text
              @click="handleEdit(item)"
              >重命名</el-button
            >

            <el-popconfirm
              title="是否删除该图片？"
              confirmButtonText="确认"
              cancelButtonText="取消"
              @confirm="handleDelete(item.id)"
            >
              <template #reference>
                <el-button class="!m-0" type="primary" size="small" text
                  >删除</el-button
                >
              </template>
            </el-popconfirm>
          </div>
        </el-card>
      </el-col>
    </el-row>
    <div v-else>
      <el-empty :image-size="200" />
    </div>
  </div>
  <div class="bottom">
    <el-pagination
      background
      layout="prev, pager,next"
      :total="total"
      :current-page="pages"
      :page-size="limit"
      @current-change="changePage"
    />
  </div>

  <Drawer ref="imgDrawerRef" title="上传图片" @submit="submit">
    <!-- <el-upload drag :action="uploadImageAction" multiple :headers="{
            token
        }" name="img" :data="{'image_class_id':classId}" :on-success="uploadSuccess" :on-error="uploadError">
            <el-icon class="el-icon--upload">
                <upload-filled />
            </el-icon>
            <div class="el-upload__text">
                Drop file here or <em>click to upload</em>
            </div>
            <template #tip>
                <div class="el-upload__tip">
                    jpg/png files with a size less than 500kb
                </div>
            </template>
        </el-upload> -->
    <UploadFile
      :data="{ image_class_id: classId }"
      @error="uploadError"
      @success="uploadSuccess"
    ></UploadFile>
  </Drawer>
</template>

<script setup>
import Drawer from "@/components/Drawer/index.vue";
import UploadFile from "@/components/UploadFile.vue";
import { getImageList, delImage, editImageName } from "@/api/image";
import { ref, reactive, computed } from "vue";
import { showModal, Toast } from "@/utils/utils.js";

const props = defineProps({
  openChoose: {
    type: Boolean,
    default: false,
  },
  imgLimit: {
    type: Number,
    default: 1,
  },
});

let pages = ref(1);
let total = ref(0);
let limit = ref(10);
let imageList = ref([]);
let classId = ref(0);
const loading = ref(false);

const getData = () => {
  loading.value = true;
  getImageList(classId.value, pages.value).then((res) => {
    loading.value = false;
    imageList.value = res.data.list.map((o) => {
      o.checked = false;
      return o;
    });
    total.value = res.data.totalCount;
  });
};
// getData()

// 分页
const changePage = (e) => {
  pages.value = e;
  getData();
};

// 初始化
const loadData = (id) => {
  classId.value = id;
  getData();
};

// 重命名

const handleEdit = (item) => {
  showModal("重命名", item.name).then(({ value }) => {
    editImageName(item.id, { name: value })
      .then((res) => {
        Toast("修改成功");
        getData();
      })
      .finally(() => {
        loading.value = false;
      });
  });
};
// 删除
const handleDelete = (id) => {
  try {
    delImage({ ids: [id] }).then((res) => {
      if (res.data) {
        Toast("删除成功");
        getData();
      } else {
        Toast("当前是演示站 不能删除", "error");
      }
    });
  } catch (error) {
    Toast("当前是演示站 不能删除", "error");
  }
};

// 添加图片
const imgDrawerRef = ref();

const addImages = () => {
  imgDrawerRef.value.openDrawer();
};

const uploadSuccess = (response) => {
  Toast("上传成功");
  getData();
  imgDrawerRef.value.closeDrawer();
};
const uploadError = () => {
  Toast("上传失败", "error");
};

const submit = () => {
  imgDrawerRef.value.closeDrawer();
};
const emit = defineEmits(["choose"]);
// 计算属性 判断是否已经选中了chang
const checkedImage = computed(() => imageList.value.filter((o) => o.checked));
// 选中图片
const handleChooseChange = (item) => {
  if (props.imgLimit === 1) {
    if (item.checked && checkedImage.value.length > 1) {
      item.checked = false;
      return Toast(`最多只能选中1张`, "error");
    }
  } else {
    if (item.checked && checkedImage.value.length > props.imgLimit.length) {
      item.checked = false;
      return Toast(`最多只能选中${props.imgLimit}张`, "error");
    }
  }

  emit("choose", checkedImage.value);
};

defineExpose({
  loadData,
  addImages,
});
</script>

<style>
.image-main .top {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 50px;
  overflow-y: auto;
}

.image-main .bottom {
  position: absolute;
  height: 50px;
  line-height: 50px;
  bottom: 0;
}

.image-title {
  position: absolute;
  top: 122px;
  left: -1px;
  right: -1px;
  @apply text-sm truncate text-gray-100 bg-opacity-50 bg-gray-800 px-2 py-1;
}
</style>
